<template>
	<view class="top-cont"></view>
	<view class="box">
		<!-- 顶部导航栏 -->
		<view class="nav-bar flex">
			<text class="nav-title">订阅</text>
			<text class="nav-icon cuIcon-time"></text>
		</view>

	</view>
	<scroll-view class="scroll-list" scroll-y="true" show-scrollbar="false">
		<view>
			<custom-card noAvatar class="margin-bottom" v-for="item in ownList" :data="item"
				@update="(field:fieldType, value:number) => handleActionUpdate(field, value, item.objectId!)"></custom-card>
		</view>
	</scroll-view>

</template>

<script setup lang="ts">
	import { ref } from 'vue';
	import type { Post } from '@/model/goods';
	import http from '@/utils/http';
	import { goodUpdate } from '@/api/createGoods_api';


	// 列表渲染
	const ownList = ref<Array<Post>>([])
	http.get('/classes/goods').then(res => {
		console.log('数据', res);
		ownList.value = res.data.results.filter(() => {
			return Math.random() > 0.5
		})
	})

	//  互动更新处理
	const contData = ref<Record<number, Post[]>>({});
	type fieldType = 'favorites' | 'comments' | 'likes'
	const handleActionUpdate = async (
		field : 'favorites' | 'comments' | 'likes',
		newValue : number,
		objectId : string
	) => {
		try {
			const goodData = { [field]: newValue }
			await goodUpdate(objectId, goodData)
			Object.values(contData.value).forEach(categoryPosts => {
				const target = categoryPosts.find(item => item.objectId === objectId);
				if (target) {
					target[field] = newValue; // 更新本地字段，触发视图刷新
				}
			});
			const hotTarget = ownList.value.find(item => item.objectId === objectId);
			if (hotTarget) {
				hotTarget[field] = newValue;
			}

			// 提示成功
			uni.showToast({ title: '操作成功', icon: 'none' });
		} catch (err) {
			console.error(`更新${field}失败`, err);
			uni.showToast({ title: '操作失败', icon: 'none' });
		}
	};
</script>

<style lang="scss">
	page {}

	.box {
		background-color: #FFFFFF;
	}

	.top-cont {
		height: 60upx;
		background-color: #FFFFFF;
	}

	.scroll-list {
		max-height: 1350upx;

	}

	.nav-bar {
		align-items: center;
		justify-content: space-between;
		height: 44px;
		padding: 0 16px;
		border-bottom: 1px solid #f5f5f5;

		.nav-title {
			font-size: 17px;
			font-weight: bold;
			color: #333;
			margin: 0 0 0 300upx;
		}

		.nav-icon {
			font-size: 20px;
			color: #333;
		}
	}
</style>